package com.macro.mall.controller;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.macro.mall.bo.AdminUserDetails;
import com.macro.mall.constans.PathConstants;
import com.macro.mall.model.AjaxResult;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.validation.Valid;
import java.util.Map;

/**
 * @author super
 * @title: OrderController
 * @description: TODO
 * @date 2020/10/12 17:33
 */
@Slf4j
@RestController
@Api(tags = "orderController", description = "订单管理")
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${host.mall.order}")
    private String HOST_MALL_ORDER;
    @Value("${host.mall.wxpay}")
    private String HOST_MALL_WXPAY;


 /*   @ApiOperation(value = "订单提交接口", notes = "订单提交接口", position = 1)
    @PostMapping(value = PathConstants.ODR_ORDRE_COMMIT,consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
    public RespVO commit(*//*@ApiParam(value = "业务流水号", required = true, name = "x-b3-traceId") @RequestHeader("x-b3-traceId") String traceId,
                         @ApiParam(value = "请求流水号", required = true, name = "x-b3-spanId") @RequestHeader("x-b3-spanId") String spanId,*//*
            @RequestBody @ApiParam(value = "请求报文", required = true) @Valid OrderCommitReqVO request) {
        log.info("订单提交请求报文：{}",request);
        String url = HOST_MALL_ORDER +PathConstants.ODR_ORDRE + PathConstants.ODR_ORDRE_COMMIT;
        ResponseEntity<RespVO> responseEntity = restTemplate.postForEntity(url, request, RespVO.class);
        return responseEntity.getBody();
    }*/

    @ApiOperation(value = "订单状态流转接口", notes = "订单状态流转接口", position = 2)
    @PostMapping(value = PathConstants.ODR_ORDRE_STATUS_UPDATE,consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
    public RespVO statusUpdate(/*@ApiParam(value = "业务流水号", required = true, name = "x-b3-traceId") @RequestHeader("x-b3-traceId") String traceId,
                               @ApiParam(value = "请求流水号", required = true, name = "x-b3-spanId") @RequestHeader("x-b3-spanId") String spanId,*/
            @RequestBody @ApiParam(value = "请求报文", required = true) @Valid OrderStatusUpdateReqVO request) {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        AdminUserDetails memberDetails = (AdminUserDetails) auth.getPrincipal();
        UmsAdmin umsAdmin = memberDetails.getUmsAdmin();
        String id = umsAdmin.getId()+"";
        String username = umsAdmin.getUsername();
        request.setUserId(id);
        request.setUserName(username);
        log.info("订单提交请求报文：{}",request);

        String url = HOST_MALL_ORDER +PathConstants.ODR_ORDRE + PathConstants.ODR_ORDRE_STATUS_UPDATE;
        ResponseEntity<RespVO> responseEntity = restTemplate.postForEntity(url, request, RespVO.class);
        if (responseEntity.getBody().getRespCode().equals("0000") && request.getTargetStatus().equals("007")) {
            String urlRefund = HOST_MALL_WXPAY + PathConstants.WXPAY + PathConstants.refund;
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlRefund);
            Map<String, Object> param = Maps.newHashMap();
            param.put("outTradeNo", request.getOrderId());
            param.entrySet().stream().forEach(o -> builder.queryParam(o.getKey(), o.getValue()));
            String restUrl = builder.build().encode().toString();
            log.debug("★★★★★★AppProdSpecController.statusUpdate   restUrl=" + restUrl);
            ResponseEntity<AjaxResult> refunt = restTemplate.getForEntity(restUrl, AjaxResult.class);
            log.info("订单提交请求报文：{}", JSONUtil.toJsonStr(refunt.getBody()));
        }
        return responseEntity.getBody();
    }

    @ApiOperation(value = "订单详细信息查询", notes = "订单详细信息查询", position = 3)
    @PostMapping(value = PathConstants.ODR_ORDRE_DETAILS_QUERY,consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
    public ResposeVO<OdrOrder> queryOdrOrderDetails(/*@ApiParam(value = "业务流水号", required = true,name = "x-b3-traceId") @RequestHeader("x-b3-traceId") String traceId,
                                                    @ApiParam(value = "请求流水号", required = true,name = "x-b3-spanId") @RequestHeader("x-b3-spanId") String spanId,*/
            @RequestBody @ApiParam(value = "订单详情查询请求报文", required = true) @Valid QueryOdrOrderDetailsReqVO request) {
        log.info("订单提交请求报文：{}",request);
        String url = HOST_MALL_ORDER +PathConstants.ODR_ORDRE + PathConstants.ODR_ORDRE_DETAILS_QUERY;
        ResponseEntity<ResposeVO> responseEntity = restTemplate.postForEntity(url, request, ResposeVO.class);
        return responseEntity.getBody();
    }

    @ApiOperation(value = "订单列表查询", notes = "订单列表查询", position = 4)
    @PostMapping(value = PathConstants.ODR_ORDRE_LIST_QUERY,consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
    public ResposeListVO<OdrOrder> queryOdrOrderList(/*@ApiParam(value = "业务流水号", required = true,name = "x-b3-traceId") @RequestHeader("x-b3-traceId") String traceId,
                                                               @ApiParam(value = "请求流水号", required = true,name = "x-b3-spanId") @RequestHeader("x-b3-spanId") String spanId,*/
            @RequestBody @ApiParam(value = "请求报文", required = true) @Valid QueryOdrOrderReqVO request) {
        log.info("订单提交请求报文：{}",request);
        String url = HOST_MALL_ORDER +PathConstants.ODR_ORDRE + PathConstants.ODR_ORDRE_LIST_QUERY;
        ResponseEntity<ResposeListVO> responseEntity = restTemplate.postForEntity(url, request, ResposeListVO.class);
        return responseEntity.getBody();
    }

    @ApiOperation(value = "订单操作日志查询", notes = "订单操作日志查询", position = 5)
    @GetMapping(value = PathConstants.ODR_ORDRE_LOG_QUERY)
    public ResposeListVO<OdrOrderFlowLog> queryOdrOrderLog(@RequestParam(value = "orderId", required = true) String orderId,
                                                           @ApiParam(value = "000-待支付、001-已取消、002-待服务、003-服务中、004-已完成、005-已退款") @RequestParam(value = "preStatus", required = false) String preStatus,
                                                           @ApiParam(value = "000-待支付、001-已取消、002-待服务、003-服务中、004-已完成、005-已退款")@RequestParam(value = "targetStatus", required = false) String targetStatus,
                                                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {


        String url = HOST_MALL_ORDER +PathConstants.ODR_ORDRE + PathConstants.ODR_ORDRE_LOG_QUERY;
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        Map<String,Object> param = Maps.newHashMap();
        param.put("orderId",orderId);
        param.put("preStatus",preStatus);
        param.put("targetStatus",targetStatus);
        param.put("pageNum",pageNum);
        param.put("pageSize",pageSize);

        param.entrySet().stream().forEach(o -> builder.queryParam(o.getKey(),o.getValue()));
        String restUrl = builder.build().encode().toString();
        log.debug("★★★★★★AppProdSpecController.listPage   restUrl="+restUrl);

        ResponseEntity<ResposeListVO> responseEntity = restTemplate.getForEntity(restUrl, ResposeListVO.class);
        return responseEntity.getBody();
    }
}
